package com.example.podapp;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.podapp.podlistClass.PodListGetSet;
import InternetServices.WebServiceCall;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class CaseListActivity extends Activity {
	String UserID = "", PodCount = "";
	String Data;
	String JsonResponse = "", JsonResponseCount = "";
	Button btnUpdateStatus = null, btnRefresh = null;
	List<PodListGetSet> list = new ArrayList<PodListGetSet>();
	private ProgressDialog pDialog;
	ListView listView;
	CustomerAdapter dataAdapter = null;
	public final String IBCode_Tag = "IBCode";
	public final String AwbNo_Tag = "AwbNo";
	public final String Consignee_Tag = "Consignee";
	public final String DepartmentCode_Tag = "DepartmentCode";
	public String ConsigneeName = "";
	PodListGetSet podObj;
	List<String> arrlist = new ArrayList<String>();
	TextView txtpodCount;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_case_list);
		Intent intnt = getIntent();
		UserID = intnt.getSerializableExtra("UserID").toString();
		btnRefresh = (Button) findViewById(R.id.btnRefreshStatus);
		txtpodCount = (TextView) findViewById(R.id.txtpodCount);
		btnRefresh.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(CaseListActivity.this,
						CaseListActivity.class);
				i.putExtra("UserID", UserID);
				onStop();
                finish();
                onDestroy();
				startActivity(i);
			}
		});
		listView = (ListView) findViewById(R.id.CaseList);
		AsyncWebServiceCall task = new AsyncWebServiceCall();
		task.execute();

	}

	public class AsyncWebServiceCall extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(CaseListActivity.this);
			pDialog.setMessage("Please wait...");
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			WebServiceCall webObj = new WebServiceCall();
			Map<String, String> map = new Hashtable<String, String>();
			map.put("Ecode", UserID);
			JsonResponse = webObj.webServiceMethod("GetPODList", map);
			
			if (JsonResponse != "") {
				JSONObject jsonObj;
				try {
					jsonObj = new JSONObject(JsonResponse);
					JSONArray JsonArr = jsonObj.getJSONArray("Result");
					for (int i = 0; i < JsonArr.length(); i++) {
						JSONObject jsonChild = JsonArr.getJSONObject(i);
						podObj = new PodListGetSet();
						podObj.setIBCode(jsonChild.getString(IBCode_Tag));
						podObj.setAwbNo(jsonChild.getString(AwbNo_Tag));
						podObj.setConsignee(jsonChild.getString(Consignee_Tag));
						podObj.setDepartmentcode(jsonChild
								.getString(DepartmentCode_Tag));
						list.add(podObj);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			Map<String, String> mapc = new Hashtable<String, String>();
			mapc.put("ECode", UserID);
			JsonResponseCount = webObj.webServiceMethod(
					"GetPODPacketStatusDetails", mapc);
			if (JsonResponseCount != "") {
				JSONObject jsonObj;
				try {
					jsonObj = new JSONObject(JsonResponseCount);
					JSONArray JsonArr = jsonObj.getJSONArray("Result");
					for (int i = 0; i < JsonArr.length(); i++) {
						JSONObject jsonChild = JsonArr.getJSONObject(i);
						PodCount = jsonChild.getString("Packet");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (pDialog.isShowing())
				pDialog.dismiss();
			if (list.isEmpty()) {
				AlertDialog.Builder dialog = new AlertDialog.Builder(
						CaseListActivity.this);
				dialog.setTitle("Message");
				dialog.setMessage("POD Data not Assigned.");
				dialog.setPositiveButton("OK",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								finish();
							}
						});
				//dialog.setNegativeButton("Cancel", null);
				dialog.show();
				return;
			}

			txtpodCount.setText("Packets : [" + PodCount + "]");
			dataAdapter = new CustomerAdapter();
			listView = (ListView) findViewById(R.id.CaseList);
			listView.setAdapter(dataAdapter);
			listView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					CheckBox chk = (CheckBox) arg1.findViewById(R.id.checkBox1);
					chk.performClick();
					if (chk.isChecked()) {
						chk.setChecked(true);
					} else {
						chk.setChecked(false);
					}
				}
			});
			Button btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
			btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
				String str;

				@Override
				public void onClick(View v) {
					str = "";
					for (int i = 0; i < arrlist.size(); i++) {
						if (arrlist.get(i) != null) {
							if (i == 0) {
								str += "[";
							}
							str += arrlist.get(i);
							if (i != arrlist.size() - 1) {
								str += ",";
							}
							if (i == arrlist.size() - 1) {
								str += "]";
							}
						}
					}
					Intent i = new Intent(CaseListActivity.this,
							EntryForm.class);
					i.putExtra("JsonData", str);
					i.putExtra("UserId", UserID);
					startActivity(i);
				}
			});
		}
	}

	public class CustomerAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		private class ViewHolder {
			TextView Consignee;
			TextView IBcode;
			TextView AwBno;
			TextView Departmentcode;
			CheckBox Checkbox;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				LayoutInflater inflater = (LayoutInflater) CaseListActivity.this
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.podtextview, parent,
						false);
				holder = new ViewHolder();
				holder.Consignee = (TextView) convertView
						.findViewById(R.id.txtconsignee);
				holder.IBcode = (TextView) convertView
						.findViewById(R.id.txtIbcode);
				holder.AwBno = (TextView) convertView
						.findViewById(R.id.txtAwbno);
				holder.Departmentcode = (TextView) convertView
						.findViewById(R.id.txtdepartmentcode);
				holder.Checkbox = (CheckBox) convertView
						.findViewById(R.id.checkBox1);
				convertView.setTag(holder);
				holder.Checkbox.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						CheckBox cb = (CheckBox) v;
						TextView tb = (TextView) v;
						PodListGetSet pod = (PodListGetSet) cb.getTag();
						PodListGetSet p = (PodListGetSet) tb.getTag();
						pod.setCheckBox(cb.isChecked());
						if (cb.isChecked() == true) {
							arrlist.add("{\"AwbNo\":" + "\"" + p.GetAwbNo()
									+ "\"," + "\"IBCode\":" + "\""
									+ p.GetIBCode() + "\"," + "\"Consignee\":"
									+ "\"" + p.getConsignee() + "\"" + "}");
						} else {
							arrlist.remove("{\"AwbNo\":" + "\"" + p.GetAwbNo()
									+ "\"," + "\"IBCode\":" + "\""
									+ p.GetIBCode() + "\"," + "\"Consignee\":"
									+ "\"" + p.getConsignee() + "\"" + "}");
						}
					}
				});
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			PodListGetSet poditem = list.get(position);
			holder.IBcode.setText("IBCode:" + poditem.GetIBCode());
			holder.AwBno.setText("AwbNo:" + poditem.GetAwbNo());
			holder.Consignee.setText("Consignee:" + poditem.getConsignee());
			holder.Departmentcode.setText("DepartmentCode:"
					+ poditem.getDepartmentCode());
			holder.Checkbox.setChecked(poditem.getCheckBox());
			holder.Checkbox.setTag(poditem);
			if (position % 2 == 0) {
				convertView
						.setBackgroundResource(R.drawable.alternate_background);
			} else {
				convertView
						.setBackgroundResource(R.drawable.alternate_backgroundtwo);
			}
			return convertView;
		}
	}
}
